package com.demo.service.impl;

import com.demo.base.BaseDao;
import com.demo.base.impl.BaseServiceImpl;
import com.demo.dao.UserDao;
import com.demo.domain.User;
import com.demo.domain.UserExample;
import com.demo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author：涛
 * @Descripition：
 * @Date：2018/3/23 16:44
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User, UserExample> implements UserService {
    @Resource
    private UserDao userDao;
    
    @Override
    public BaseDao<User, UserExample> getDao() {
        return userDao;
    }
    
    @Override
    public UserExample getExample(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if(user.getId() != null) {
            criteria.andIdEqualTo(user.getId());
        }
        if(user.getUsername() != null) {
            criteria.andUsernameEqualTo(user.getUsername());
        }
        if(user.getPassword() != null) {
            criteria.andPasswordEqualTo(user.getPassword());
        }
        if(user.getRealname() != null) {
            criteria.andRealnameEqualTo(user.getRealname());
        }
        if(user.getSex() != null) {
            criteria.andSexEqualTo(user.getSex());
        }
        if(user.getGrade() != null) {
            criteria.andGradeEqualTo(user.getGrade());
        }
        if(user.getEmail() != null) {
            criteria.andEmailEqualTo(user.getEmail());
        }
        return userExample;
    }
    
    /**
     * @param order
     * @Description：查询所有用户，按id排列
     * @Author：涛哥
     * @Time：2019/1/5 21:31
     */
    @Override
    public List<User> getAllUser(String order) {
        UserExample userExample = getExample(new User());
        userExample.setOrderByClause("id " + order);
        List<User> users;
        try {
            users = getDao().selectByExample(userExample);
        } catch (Exception e) {
            LOGGER.error("查询所有用户失败！", e);
            throw e;
        }
        return users;
    }
    
    /**
     * @param username
     * @Description：按用户名前后模糊查询用户
     * @Author：涛哥
     * @Time：2019/1/5 21:31
     */
    @Override
    public List<User> getUserLikeUsername(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameLike("%" + username + "%");
        userExample.setOrderByClause("id asc");
        List<User> users;
        try {
            users = getDao().selectByExample(userExample);
        } catch (Exception e) {
            LOGGER.error("按用户名前后模糊查询用户失败！", e);
            throw e;
        }
        return users;
    }
}
